package com.qire.manhua.model.viewModel.impl;

import android.app.Activity;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;

import com.qire.antscore.annotation.PropertyObserve;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.model.entity.UserEntity;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.utils.CountDownTimerBuilder;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.R;
import com.qire.manhua.dal.service.PasswordChangeGuideService;
import com.qire.manhua.databinding.ActivityPasswordChangeGuideBinding;
import com.qire.manhua.model.enumeration.AccountBusinessPanelLayout;
import com.qire.manhua.model.viewModel.IPasswordChangeGuideViewModel;

import net.yslibrary.android.keyboardvisibilityevent.util.UIUtil;

import java.util.Arrays;
import java.util.Stack;
import java.util.concurrent.TimeUnit;

public class PasswordChangeGuideViewModel extends BaseViewModel<IPasswordChangeGuideViewModel> {

    private PasswordChangeGuideService changeGuideService = new PasswordChangeGuideService(this);

    //保存接口返回的验证码是什么类型，原密码或是短信验证码
    private String validateType = "";
    //保存接口返回的验证码，用来做修改密码等需要验证的接口操作
    private String validateCode = "";

    private ActivityPasswordChangeGuideBinding viewDataBinder;

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param viewDataBinder 页面数据绑定器
     */
    public void onAddition(ActivityPasswordChangeGuideBinding viewDataBinder) {
        this.viewDataBinder = viewDataBinder;
        initPanelLayout();
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        changeGuideService = null;
        viewDataBinder = null;
    }
    //endregion #附加管理 end

    //region    #业务数据 begin

    public boolean passwordIsValid(String oldPassword) {
        return StringUtil.notEmpty(oldPassword) && oldPassword.length() >= 8;
    }

    public boolean validateOldPassword() {
        String oldPassword = getToValue("oldPassword");
        if(passwordIsValid(oldPassword)) {
            changeGuideService.validateOldPassword(oldPassword);
            return true;
        }
        return false;
    }

    public void setValidateInfo(String validateCode, String validateType) {
        this.validateType = validateType;
        this.validateCode = validateCode;
    }

    public void fetchVerificationCode() {
        if(UserEntity.self.haveBindMobile()) {
            startCountDown();
            requestVerifyCode1Focus();
            changeGuideService.fetchVerificationCode(UserEntity.self.getMobile());
        } else {
            ToastHelper.showToast("未绑定手机号请先绑定才能接收验证码！");
        }
    }

    public void checkVerificationCode() {
        if(verifyCodeIsValid()) {
            changeGuideService.checkVerificationCode(UserEntity.self.getMobile(), verifyCode());
        } else {
            ToastHelper.showToast("无效的验证码");
        }
    }

    public void updatePasswordAction() {
        String newPassword = getToValue("newPassword");
        String newPassword1 = getToValue("newPassword1");

        boolean passwordIsValid = passwordIsValid(newPassword) && passwordIsValid(newPassword1);

        if(!passwordIsValid) {
            ToastHelper.showToast("无效的密码"); return;
        }

        if(ObjectUtil.notEquals(newPassword, newPassword1)) {
            ToastHelper.showToast("确认密码不一致"); return;
        }

        changeGuideService.updatePasswordAction(UserEntity.self.getMobile(), newPassword, validateCode, validateType);
    }

    //endregion #业务数据 end

    //region    #面板操作 begin
    private final Stack<AccountBusinessPanelLayout> pageStack = new Stack<>();
    private AccountBusinessPanelLayout currentPanelLayout = null;

    public void initPanelLayout() {
        pageStack.clear();
        set("phoneNumber", UserEntity.self.getMobile());
        onOldPasswordChange("");
        refreshChangePasswordBtn("", "");

        AccountBusinessPanelLayout.ModifyPassword.addNext(AccountBusinessPanelLayout.ModifyPwdFinishHint);
        AccountBusinessPanelLayout.ModifyPasswordWay.addNext(AccountBusinessPanelLayout.ModifyPassword);
        gotoPage(AccountBusinessPanelLayout.ModifyPasswordWay);
    }

    public boolean backPage() {
        // 栈空为首页和当前到结束页时直接退出
        if(pageStack.isEmpty() || currentPanelLayout.isFinish) {
            return true;
        }
        refreshPage(pageStack.pop());
        return false;
    }

    public void nextPage() {
        if(currentPanelLayout == null)
            return;
        if(currentPanelLayout.next() == null) {
//            activity.finish();
            return;
        }
        if(currentPanelLayout.needRecycle()) {
            pageStack.push(currentPanelLayout);
        }
        refreshPage(currentPanelLayout.next());
    }


    public void gotoPage(AccountBusinessPanelLayout page) {
        if(currentPanelLayout != null) {
            pageStack.push(currentPanelLayout);
        }
        refreshPage(page);
    }

    private void refreshPage(AccountBusinessPanelLayout page) {
        this.currentPanelLayout = page;
        hideKeyBoard();
        resetVerifyCode();

        int[] layoutVisible = new int[5];
        Arrays.fill(layoutVisible, View.GONE);
        switch (currentPanelLayout) {
            case ModifyPasswordWay:
                layoutVisible[0] = View.VISIBLE; break;
            case SendVerifyCode:
                layoutVisible[1] = View.VISIBLE; break;
            case CodeVerify:
                layoutVisible[2] = View.VISIBLE; break;
            case ModifyPassword:
                layoutVisible[3] = View.VISIBLE; break;
            case ModifyPwdFinishHint:
                layoutVisible[4] = View.VISIBLE; break;
        }
        set("layoutVisible", layoutVisible);
        set("title", currentPanelLayout != null ? currentPanelLayout.pageTitle : "手机登录/注册");
    }

    private void hideKeyBoard() {
        UIUtil.hideKeyboard((Activity) viewDataBinder.getRoot().getContext());
    }
    //endregion #面板操作 end

    //region    #旧密码操作 begin
    @PropertyObserve(name = "oldPassword")
    public void onOldPasswordChange(String oldPassword) {
        boolean passwordIsValid = passwordIsValid(oldPassword);
        set("oldPasswordVerifyButtonEnabled", passwordIsValid);
        set("oldPasswordVerifyButtonBackground", passwordIsValid ? R.drawable.app_common_button_yellow : R.drawable.app_password_change_bg_grey_translucent);
        set("oldPasswordVerifyButtonTextColor", passwordIsValid ? "#1f1f1f" : "#d6d6d6");
    }
    //endregion #旧密码操作 end

    //region    #验证码操作 begin
    private int verifyCode1 = -1;
    private int verifyCode2 = -1;
    private int verifyCode3 = -1;
    private int verifyCode4 = -1;

    /** 验证码计时器*/
    private CountDownTimer timer;

    public void requestVerifyCode1Focus() {
        final EditText focusView = viewDataBinder.verifyCode1;
        focusView.requestFocus();
        focusView.postDelayed(()-> UIUtil.showKeyboard(focusView.getContext(), focusView), 300);
    }
    /** 获取验证码倒计时*/
    private void startCountDown() {
        if(ObjectUtil.nonNull(timer)) {
            timer.cancel();
            timer.onFinish();
        }

        setFetchVerifyCodeTextEnabled(false);
        timer = CountDownTimerBuilder.build(60, 1, TimeUnit.SECONDS)
                .addTickCallBack((countDownTime, timeUnit) -> {
                    setFetchVerifyCodeText(String.format("重新获取(%ss)", countDownTime--));
                    return countDownTime;
                })
                .addFinishCallBack((countDownTime, timeUnit) -> {
                    resetGetCodeButton();
                    return countDownTime;
                }).start();
    }
    /** 恢复获取验证码按钮*/
    private void resetGetCodeButton() {
        if(ObjectUtil.nonNull(timer)) {
            timer.cancel();
        }
        setFetchVerifyCodeText("重新获取");
        setFetchVerifyCodeTextEnabled(true);
    }

    private void setFetchVerifyCodeText(CharSequence fetchVerifyCodeText) {
        set("fetchVerifyCodeText", fetchVerifyCodeText);
    }

    private void setFetchVerifyCodeTextEnabled(boolean fetchVerifyCodeTextEnabled) {
        set("fetchVerifyCodeTextColor", fetchVerifyCodeTextEnabled ? "#ff9204" : "#aeaeae");
        set("fetchVerifyCodeTextEnabled", fetchVerifyCodeTextEnabled);
    }

    private void resetVerifyCode() {
        setVerifyCode1("");
        setVerifyCode2("");
        setVerifyCode3("");
        setVerifyCode4("");
        resetGetCodeButton();
    }

    private String verifyCode() {
        return String.format("%s%s%s%s", verifyCode1, verifyCode2, verifyCode3, verifyCode4);
    }

    private boolean verifyCodeIsValid() {
        return verifyCode1 >= 0 && verifyCode2 >= 0 && verifyCode3 >= 0 && verifyCode4 >= 0;
    }

    /**
     * 刷新验证码确认按钮状态
     */
    private void refreshVerifyBtn() {
        put("verifyBtnEnabled", verifyCodeIsValid());
        put("verifyBtnTextColor", verifyCodeIsValid() ? "#423300" : "#aeaeae");
        put("verifyBtnBackground", verifyCodeIsValid() ? R.drawable.app_accounts_associated_bg_yellow : R.drawable.app_accounts_associated_bg_gray);
    }

    /**
     * 以下是4个验证码输入框的状态监听，如果输入框内容发生改变则会触发观察者消息
     */
    @PropertyObserve(name = "verifyCode1")
    public void setVerifyCode1(String verifyCode1) {
        try {
            int codeValue = Integer.valueOf(verifyCode1);
            // 解决光标位置问题导致可能最新输入的字符在旧字符前需要判断故做一下数值运算处理，始终使用最新值替换旧值；
            if(codeValue != this.verifyCode1) {
                this.verifyCode1 = codeValue % 10 == this.verifyCode1 ? codeValue / 10 : codeValue % 10;
            }
            viewDataBinder.verifyCode2.requestFocus();
        } catch(Exception e) {
            this.verifyCode1 = -1;
        }
        refreshVerifyBtn();
    }
    @PropertyObserve(name = "verifyCode2")
    public void setVerifyCode2(String verifyCode2) {
        try {
            int codeValue = Integer.valueOf(verifyCode2);
            if(codeValue != this.verifyCode2) {
                this.verifyCode2 = codeValue % 10 == this.verifyCode2 ? codeValue / 10 : codeValue % 10;
            }
            viewDataBinder.verifyCode3.requestFocus();
        } catch(Exception e) {
            this.verifyCode2 = -1;
            viewDataBinder.verifyCode1.requestFocus();
        }
        refreshVerifyBtn();
    }
    @PropertyObserve(name = "verifyCode3")
    public void setVerifyCode3(String verifyCode3) {
        try {
            int codeValue = Integer.valueOf(verifyCode3);
            if(codeValue != this.verifyCode3) {
                this.verifyCode3 = codeValue % 10 == this.verifyCode3 ? codeValue / 10 : codeValue % 10;
            }
            viewDataBinder.verifyCode4.requestFocus();
        } catch(Exception e) {
            this.verifyCode3 = -1;
            viewDataBinder.verifyCode2.requestFocus();
        }
        refreshVerifyBtn();
    }
    @PropertyObserve(name = "verifyCode4")
    public void setVerifyCode4(String verifyCode4) {
        try {
            int codeValue = Integer.valueOf(verifyCode4);
            if(codeValue != this.verifyCode4) {
                this.verifyCode4 = codeValue % 10 == this.verifyCode4 ? codeValue / 10 : codeValue % 10;
            }
        } catch(Exception e) {
            this.verifyCode4 = -1;
            viewDataBinder.verifyCode3.requestFocus();
        }
        refreshVerifyBtn();
    }
    //endregion #验证码操作 end

    //region    #新密码操作 begin
    @PropertyObserve(name = "newPassword")
    public void onNewPasswordChange(String newPassword) {
        refreshChangePasswordBtn(newPassword, getToValue("newPassword1"));
    }
    @PropertyObserve(name = "newPassword1")
    public void onNewPassword1Change(String newPassword1) {
        refreshChangePasswordBtn(getToValue("newPassword"), newPassword1);
    }
    private void refreshChangePasswordBtn(String newPassword, String newPassword1) {
        boolean passwordIsValid = passwordIsValid(newPassword) && passwordIsValid(newPassword1);
        set("changePasswordBtnEnabled", passwordIsValid);
        set("changePasswordBtnTextColor", passwordIsValid ? "#1f1f1f" : "#d6d6d6");
        set("changePasswordBtnBackground", passwordIsValid ? R.drawable.app_common_button_yellow : R.drawable.app_password_change_bg_grey_translucent);
    }
    //endregion #新密码操作 end


}
